<?php

session_start();
require_once('../config.php');

require_once($CONFIG->datadir.'/bot/lib/ActiveRecordSystem.php');
require_once($CONFIG->datadir.'/bot/lib/ActiveRecordLang.php');
require_once($CONFIG->datadir.'/bot/lib/Blog.php');
require_once($CONFIG->datadir.'/bot/lib/Entry.php');
require_once($CONFIG->datadir.'/bot/lib/LocaleLang.php');

// Default language, it will change
$_SESSION["lang"] = $CONFIG->defaultlanguage;

// Main DB instance
$DB = new DB();

// Language specific DB instance
$DB_LANG = new DB_lang();

$timestart = time();

System::loadPendingBlogs();

$i = 0;
while ($i < $CONFIG->Npetitions) {

    // Reload next links
    if (empty(System::$blogs[$i])) {
        System::loadPendingBlogs($i);
    }

    $blog = new Blog(System::$blogs[$i]['id'], System::$blogs[$i]['name'], System::$blogs[$i]['url']);
    $allentriesurl = $blog->dbobj->url.'search?max-results='.$CONFIG->entriesperblog;

    // If could not be parsed mark it as visited and next
    if (!$blog->getBlogHtml($allentriesurl)) {
        $blog->markAsVisited();
        
    // Let get the links pointing to other blogs, the $blog entries and his labels
    } else {
        
    	$blog->saveBlogsLinks();
        
    	// Get the blog locale
        $locale = $blog->getLocale();
        $blog->dbobj->localeid = System::getLocaleId($locale);
        $blog->update();

        // The blog should only be parsed if there is a database for his language
        $bloglang = substr($locale, 0, 2);

        if (array_key_exists($bloglang, $CONFIG->availablelanguages)) {
        	
        	// Change DB (test performance)
        	if ($bloglang != $_SESSION['lang']) {
	        	$_SESSION['lang'] = $bloglang;
	        	unset($DB_LANG);
	        	$DB_LANG = new DB_lang();
        	} 
        	
        	$blog->getEntries();
        	$blog->markAsVisited();
        }
        
    }

    if ($CONFIG->sleep) {
        sleep($CONFIG->sleep);
    }
    
    $i = $i + 1;
}


$timeend = time();
echo date('i:s', $timeend - $timestart).' mins:secs<br>';

echo '<br>Petitions: '.$CONFIG->Npetitions;
echo '<br>Next link: '.System::$blogs[$i]['url'].'<br><br>';
